package net.qhzw.vip.qiyu.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import net.qhzw.vip.qiyu.dto.WxLoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@RestController
public class UserInfoController {


    @Value("${dts.wx.appId}")
    private String appId; // "wx239f820e1ebec86a";

    @Value("${dts.wx.appSecret}")
    private String appSecret; // "8bf83e13c3e5ddcdac402e8bf1dab715";

    /**
     * 当前的登录的用户对象
     *
     * @param principal
     * @return
     */
    @GetMapping("/user/info")
    public Principal userInfo(Principal principal) {
        // 使用ThreadLocal来实现的
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return principal;
    }


    @ApiOperation(value = "获取openID")
    @GetMapping("user/loginByWeixin")
    public String getOpenId(@RequestParam String code) {
        WxMaInMemoryConfig config = new WxMaInMemoryConfig();
        config.setAppid(appId);
        config.setSecret(appSecret);
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(config);
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = service.getUserService().getSessionInfo(code);
            //sessionKey = result.getSessionKey();
            openId = result.getOpenid();
            return openId;
        } catch (WxErrorException e) {
            throw new ApiException("调用微信官方接口失败，获取openId失败！");
        }
    }


}
